package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-05-24 10:33:57
 */
public class HotCode012 {
    public static void main(String[] args) {
        String s = "ADOBECODEBANC", t = "ABC";
        HotCode012 hotCode = new HotCode012();
        System.out.println(hotCode.minWindow(s, t));
    }

    Map<Character, Integer> mapS = new HashMap<>();
    Map<Character, Integer> mapT = new HashMap<>();
    public String minWindow(String s, String t) {
        if (s.length() < t.length()) {
            return "";
        }
        for (int i = 0; i < t.length(); i++) {
            mapT.put(t.charAt(i), mapT.getOrDefault(t.charAt(i), 0) + 1);
        }
        int left = 0, right = 0;
        int[] index = {-1, -1};
        while (right < s.length()) {
            mapS.put(s.charAt(right), mapS.getOrDefault(s.charAt(right), 0) + 1);
            while (left <= right && check()) {
                if (index[0] == -1 || (right - left) < (index[1] - index[0])) {
                    index[0] = left;
                    index[1] = right;
                }
                mapS.put(s.charAt(left), mapS.get(s.charAt(left)) - 1);
                left++;
            }
            right++;
        }
        return index[0] == -1 ? "" : s.substring(index[0], index[1] + 1);
    }

    public boolean check() {
        for (Character c : mapT.keySet()) {
            if (!mapS.containsKey(c)) {
                return false;
            }
            if (mapS.get(c) < mapT.get(c)) {
                return false;
            }
        }
        return true;
    }
}
